﻿<template>
  <div>
    <el-dialog v-drag :title = 'dialogTitle' :visible.sync = 'dialogFormVisible' width = '40%' @close = "closeDialog"
    :close-on-click-modal = 'false'>
      <el-form :model = "ruleForm" ref = "ruleForm" :label-width = 'labelWidth' :rules = 'rules'>
        <el-form-item label = "来源表名称：">
           <el-input v-model = "ruleForm.fromTableName" disabled></el-input>
        </el-form-item>
        <el-form-item label = "目标表名称：" prop = 'toTableName'>
          <el-select v-model = 'ruleForm.toTableName' placeholder = "请选择目标表名称" @change = 'toTableChange'>
            <el-option v-for = '(item, index) in tableList' :key = 'index' :disabled = 'item.metauid === currentTable.metauid' :label = "item.metaname"
            :value = "item.metauid"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label = "是否判断存在：">
          <el-switch v-model = 'ruleForm.isJustify'></el-switch>
        </el-form-item>
        <el-form-item label = "复制栏位信息：">
          <div class = 'page_tableContent' style = 'min-height:100px'>
            <div class = 'addBtn'>
              <p @click = 'addCopyColumns()'><i class = 'iconfont icon-add'></i>新增栏位信息</p>
            </div>
            <el-table :data = 'columnTable' style='width:100%;margin-bottom:0' empty-text = '暂无栏位信息，请立即添加' border stripe>
              <el-table-column align = 'center' label='来源表栏位名称'>
                <template slot-scope = 'scope'>
                  <el-select v-model = "scope.row.fromColumn" placeholder = "请选择"
                  @focus = 'columnSelect(scope.row)' filterable>
                    <el-option v-for = '(item, index) in selectColumns' :key = 'index'
                    :label = "item.column_desc ? item.column_name + '(' + item.column_desc + ')' : item.column_name" :value = "item.column_name"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align = 'center' label = '目标表栏位名称'>
                <template slot-scope = 'scope'>
                  <el-select v-model = "scope.row.toColumn" placeholder = "请选择"
                  @focus = 'showToColumns(scope.row)' filterable>
                    <el-option v-for = '(item, index) in selectToColumns' :key = 'index'
                    :label = "item.column_desc ? item.column_name + '(' + item.column_desc + ')' : item.column_name" :value = "item.column_name"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align = "center" label = '操作' width = '70'>
                <template slot-scope = "scope">
                  <el-button type = 'text' @click = "handleDeleteColums(scope.$index)"><i class='iconfont icon-shanchu'></i>删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item label = "过滤条件：">
          <div class = 'page_tableContent' style = 'min-height:100px'>
            <div class = 'addBtn'>
              <p @click = 'addFilterColumns()'><i class='iconfont icon-add'></i>新增过滤条件</p>
            </div>
            <el-table :data = 'filterTable' style = 'width:100%;margin-bottom:0' empty-text = '暂无过滤条件信息，请立即添加' border stripe class='editTable'>
              <el-table-column align = 'center' label = '来源表栏位名称'>
                <template slot-scope = 'scope'>
                  <el-select v-model = "scope.row.column" placeholder = "请选择" filterable>
                    <el-option v-for = '(item, index) in currentTable.columns' :key = 'index'
                    :label = "item.column_desc ? item.column_name + '(' + item.column_desc + ')' : item.column_name" :value="item.column_name"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align = 'center' label = '操作符' width = '80px'>
                <template slot-scope = 'scope'>
                  <el-select v-model = "scope.row.op" placeholder = "请选择">
                    <el-option label = '模糊查询' value = 'like'></el-option>
                    <el-option label = '精确查询' value = '='></el-option>
                    <el-option label = '大于' value = '>'></el-option>
                    <el-option label = '大于等于' value = '>='></el-option>
                    <el-option label = '小于' value = '<'></el-option>
                    <el-option label = '小于等于' value = '<='></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column align = 'center' label = '值'>
                <template slot-scope = 'scope'>
                  <el-input v-model = "scope.row.value" placeholder = "请输入"></el-input>
                </template>
              </el-table-column>
              <el-table-column align = "center" label = '操作' width = '70'>
                <template slot-scope = "scope">
                  <el-button type = 'text' @click = "handleDeleteFilter(scope.$index)"><i class = 'iconfont icon-shanchu'></i>删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-form-item>
        <el-form-item class = 'form_noLeftMargin'>
          <el-button type = 'info' @click = "resetForm ('ruleForm')">取 消</el-button>
          <el-button type = "primary" @click = "submitForm ('ruleForm')">确 定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  props: ['copyDataDialog', 'currentTable', 'tableList'],
  data () {
    return {
      dialogTitle: '一个元数据表数据到另一个元数据表',
      dialogFormVisible: false,
      labelWidth: '110px',
      ruleForm: {
        fromTableName: '',
        toTableName: '',
        isJustify: false
      },
      rules: {
        toTableName: [
          {required: true, message: '目标表名称不能为空', trigger: 'blur'}
        ]
      },
      columnTable: [],
      // 选择源栏位
      selectColumns: [],
      // 选择目标栏位
      selectToColumns: [],
      // 过滤栏位
      filterTable: []
    }
  },
  methods: {
    // 目标表改变时
    toTableChange (val) {
      this.columnTable = []
      // 目标表一选中就自动带出和来源表名称相同的栏位---复制栏位信息时
      if (val) {
        // 目标表的所有栏位
        let allToColumns = this.allToColumns(val)
        // 来源表的所有栏位
        let allFromColumns = JSON.parse(JSON.stringify(this.currentTable.columns))
        if (allToColumns.length && allFromColumns.length) {
          allToColumns.forEach(item => {
            for (let i = 0; i < allFromColumns.length; i++) {
              if (item.column_name === allFromColumns[i].column_name) {
                let obj = {
                  fromColumn: allFromColumns[i].column_name,
                  toColumn: item.column_name
                }
                this.$set(this.columnTable, this.columnTable.length, obj)
                break
              }
            }
          })
        }
      }
    },
    // 添加复制栏位
    addCopyColumns () {
      if (this.ruleForm.toTableName) {
        this.columnTable.push({
          fromColumn: '',
          toColumn: ''
        })
      } else {
        this.$message({
          message: '请先选择目标表名称',
          type: 'warning'
        })
      }
    },
    // 删除复制的栏位时
    handleDeleteColums (index) {
      this.$confirm('此操作将永久删除该栏位, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'el-button--info'
      }).then(() => {
        this.columnTable.splice(index, 1)
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      }).catch(() => {})
    },
    // 选择来源表单栏位字段时
    columnSelect (row) {
      // 清空来源表的下拉数据源
      this.selectColumns = []
      // 对来源表的所有栏位进行遍历，如果复制栏位信息表中的来源表栏位字段已经包含该字段，那么该字段将不出现在下拉列表中（本身除外）
      this.currentTable.columns.forEach(totalVal => {
        let surePush = true
        if (this.columnTable.length) {
          this.columnTable.forEach(val => {
            if (val.fromColumn === totalVal.column_name && row.fromColumn !== val.fromColumn) {
              surePush = false
            }
          })
        }
        if (surePush) {
          this.selectColumns.push(totalVal)
        }
      })
    },
    // 选择目标栏位
    showToColumns (row) {
      if (this.ruleForm.toTableName) {
        // 清理目标栏位的下拉数据源
        this.selectToColumns = []
        // 对目标源表的所有栏位进行遍历，如果复制栏位信息表中的目标表栏位字段已经包含该字段，那么该字段将不出现在下拉列表中（本身除外）
        let allColumns = this.allToColumns(this.ruleForm.toTableName)
        if (allColumns.length) {
          allColumns.forEach(totalVal => {
            let surePush = true
            if (this.columnTable.length) {
              this.columnTable.forEach(val => {
                if (val.toColumn === totalVal.column_name && row.toColumn !== val.toColumn) {
                  surePush = false
                }
              })
            }
            if (surePush) {
              this.selectToColumns.push(totalVal)
            }
          })
        }
      } else {
        this.$message({
          message: '请先选择目标表名称',
          type: 'warning'
        })
      }
    },
    // 获取目标表的栏位
    allToColumns (metauid) {
      let columns = []
      if (this.tableList.length) {
        this.tableList.forEach(val => {
          if (val.metauid === metauid) {
            columns = val.columns
          }
        })
      }
      return columns
    },
    // 添加过滤栏位
    addFilterColumns () {
      this.filterTable.push({
        column: '',
        op: '',
        value: ''
      })
    },
    // 删除过滤的栏位时
    handleDeleteFilter (index) {
      this.$confirm('此操作将永久删除该栏位, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        cancelButtonClass: 'el-button--info'
      }).then(() => {
        this.filterTable.splice(index, 1)
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      }).catch(() => {})
    },
    // 点击取消按钮时
    resetForm (forms) {
      this.$refs[forms].resetFields()
      this.$emit('giveUpCopyData')
    },
    // 点击上部的X关闭弹窗时
    closeDialog () {
      this.$refs.ruleForm.resetFields()
      this.$emit('giveUpCopyData')
    },
    // 将复制的栏位信息转为base64
    getColumnsBase64 () {
      let stringBase64 = ''
      if (this.columnTable.length) {
        let objEXam = {}
        this.columnTable.forEach(val => {
          objEXam[val.fromColumn] = val.toColumn
        })
        stringBase64 = btoa(encodeURIComponent(JSON.stringify(objEXam)))
      }
      return stringBase64
    },
    // 将过滤条件转为base64
    getFilterBase64 () {
      let stringBase64 = ''
      if (this.filterTable.length) {
        stringBase64 = btoa(encodeURIComponent(JSON.stringify(this.filterTable)))
      }
      return stringBase64
    },
    // 点击确定提交的按钮时
    submitForm (forms) {
      this.$refs[forms].validate((valid) => {
        if (valid) {
          this.$patch('/metadata/' + this.currentTable.metauid + '/copydata', {
            to_id: this.ruleForm.toTableName,
            if_not_exists: this.ruleForm.isJustify,
            columns: this.getColumnsBase64(),
            where: this.getFilterBase64()
          }).then(data => {
            if (data.data.result.code === 'failed') {
              this.$message({
                message: data.data.result.msg,
                type: 'warning'
              })
            } else if (data.data.result.code === 'success') {
              this.$message({
                message: '元数据表数据复制成功',
                type: 'success'
              })
              this.$refs[forms].resetFields()
              this.$emit('sureCopyData')
            }
          }).catch(error => {
            console.log(error)
          })
        } else {
          return false
        }
      })
    }
  },
  watch: {
    copyDataDialog: {
      handler: function (val, oldVal) {
        this.dialogFormVisible = val
        if (val) {
          this.ruleForm.fromTableName = this.currentTable.metaname
          this.ruleForm.toTableName = ''
          this.ruleForm.isJustify = false
          this.columnTable = []
          this.filterTable = []
        }
      },
      deep: true
    }
  }
}
</script>
